package cn.bon.websocket.pusher;


import cn.bon.common.adapter.JsonSerializerAdapter;
import cn.bon.websocket.config.JsonUtilConfig;
import cn.bon.websocket.interfaces.MessagePusher;
import cn.bon.websocket.pojo.dto.MessageDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import jakarta.annotation.Resource;

/**
 * @author: dronff
 * @description:
 * @CreateTime: 2023/12/12 15:59
 **/

public class DefaultChannelPusher implements MessagePusher {
    private Channel channel;
    @Resource
    private JsonSerializerAdapter jsonSerializerAdapter;
    public DefaultChannelPusher(Channel channel, JsonSerializerAdapter jsonSerializerAdapter){
        this.channel = channel;
        this.jsonSerializerAdapter = jsonSerializerAdapter;
    }

    @Override
    public void push(MessageDTO messageDTO) throws JsonProcessingException {
        channel.writeAndFlush(
                new TextWebSocketFrame(
                        jsonSerializerAdapter.readObjectAsJson(
                                messageDTO
                        )
                )
        );
    }

    @Override
    public void shutDown() {
        channel.close();
    }
}
